﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Dynamic;
using FluorineFx.Json;

namespace lxwmvc
{
    public static class regcontroller
    {
        /// <summary>
        /// 全局引用
        /// </summary>
        /// <param name="pb"></param>
        public static void _init(pagebase pb)
        {

        }


        /// <summary>
        /// 注册时候发送验证码
        /// </summary>
        /// <param name="pb"></param>
        [json]
        public static void regsendcode(pagebase pb)
        {
            //获取到手机号
            var sjh = pb.v_ss("shoujihao");
            #region
            //while (true)
            //{
            //    try
            //    {
            //        ifcheck(json, core_reg.IsMobilePhone(sjh), "请输入合法的手机号!");
            //        break;
            //    }
            //    catch {
            //        break;
            //    }
            //}
            #endregion
            pb.ifcheck(!core_reg.IsMobilePhone(sjh), "请输入合法的手机号!");
            //判断手机号是否已经存在
            var user_id = core_regdb.getUserByMobile(sjh);
            pb.ifcheck(user_id > 0, "该手机号已经注册!");

            //记录用户信息
            //pb.Session["code_user_id"] = user_id;
            //var oldshoujihao = pb.Session["_oldshoujihao"]??"";
            var oldCodeTime = pb.Session["_CodeTime"] ?? "";
            //如果已经发送 就验证发送了多长时间
            if (oldCodeTime != null && oldCodeTime.tostr() != "")// && pb.Session["code_user_id"] != null)
            {
                //string time = supermodel
                //    .create("SysUser_kuozhan")
                //    .select("_CodeTime")
                //    .where("user_id='" + pb.Session["code_user_id"] + "'").one<string>();
                TimeSpan CodeTime = oldCodeTime.todatetime() - DateTime.Now;
                pb.ifcheck(oldCodeTime.todatetime() > DateTime.Now, "您已获取验证码!请" + CodeTime.Minutes + "分钟后重试!");
            }

            string code = core_reg.GetRandomString(4);
            var senSMS = "非常感谢您注册，您的验证码是 " + code + "。请尽快完成操作。如非本人操作，请忽略！";
            ////发送短信验证码
            //if (PaheUrl == "reg.html")//判断是 注册页面
            //{
            //    senSMS = "非常感谢您注册，您的验证码是 " + code + "。请尽快完成操作。如非本人操作，请忽略！";
            //}
            //if (PaheUrl == "user_updatephone.html")//判断是 修改绑定手机页面
            //{
            //    senSMS = "修改绑定手机，您的验证码是 " + code + "。请尽快完成操作。如非本人操作，请忽略！";
            //}
            //if (PaheUrl == "findpwd.html")//判断是 修改找回密码页面
            //{
            //    senSMS = "找回密码，您的验证码是 " + code + "。请尽快完成操作。如非本人操作，请忽略！";
            //}
            pb.ifcheck(!core_sms.SendMsg(sjh, senSMS), "发送短信验证码失败!");

            pb.Session["_code"] = code;
            pb.Session["_CodeTime"] = DateTime.Now.AddMinutes(5);//5分钟
            pb.Session["_phonecode"] = sjh + "_" + code;
            pb.Session["_codesum"] = 5;//最多次数

            BaseJson json = pb.JSON<BaseJson>();
            //发送成功
            json.msg = "发送成功!";
        }

        /// <summary>
        /// 提交用户信息,注册
        /// </summary>
        /// <param name="pb"></param>
        [json]
        public static void regsubmit(pagebase pb)
        {
            //获取用户信息
            dynamic body = pb.bodyjson().tosm();
            string shoujihao = body.shoujihao??"";
            pb.ifcheck(!core_reg.IsMobilePhone(shoujihao), "请输入合法的手机号!");

            string mima = body.mima.tostr();
            pb.ifcheck(mima.Length < 4 || mima.Length > 20, "密码输入不符合要求!");

            string yanzhengma = body.yanzhengma??"";
            string code = (pb.Session["_code"] ?? "").tostr();
            pb.ifcheck(code == "", "验证码已经失效，请重新获取验证码!");

            int codesum = pb.Session["_codesum"].toint32();
            if (codesum <= 0)
            {
                pb.Session.Remove("_phonecode");//删除验证码
                pb.ifcheck(true, "您已经连续输错5次验证码,请重新获取!");
            }

            //防止篡改手机号
            if (pb.Session["_phonecode"].tostr() != (shoujihao.Trim() + "_" + code))
            {
                pb.Session["_codesum"] = codesum - 1;
                pb.ifcheck(true, "验证码格式不正确!\n您还有" + codesum + "次机会！");
            }

            pb.ifcheck(yanzhengma != code, "验证码输入错误，请重新输入验证码!");

            string yaoqingma = body.yaoqingma??"";
            if (yaoqingma != "")
            {
                //判断邀请码是否在数据库存在
                pb.ifcheck(core_regdb.checkYaoQingMaShiFouCunZai(yaoqingma), "你输入的邀请码不存在，你可以设置为空!");
            }

            //存储到数据库中，然后模拟登录，跳转到用户中心或者首页
            {
                body.USER_NAME = shoujihao;
                pb.ifcheck(!core_regdb.checkUserByMobile(shoujihao), "手机号已经存在!");


                body.password = cryptohelper.md5(mima).ToUpper();
                supermodel yonghu = body as supermodel;
                yonghu["USER_PRIV"] = "71";//角色ID
                yonghu["DEPT_ID"] = "303";//部门ID
                yonghu["SFLiZhi"] = "0";//是否离职
                yonghu["POST_PRIV"] = "0";//
                yonghu["NOT_LOGIN"] = "1";//普通用户注册禁止登陆OA
                yonghu["NICK_NAME"] = "";
                yonghu["MOBIL_NO"] = shoujihao.Trim();//手机号
                //插入一条记录到数据库
                var res = yonghu.saveorupdate();

                //更新user_id信息
                supermodel
                    .create("sysuser")
                    .set("user_id", res.identity)
                    .where("UID = " + res.identity)
                    .update();


                if (res.action == action.insert && res.identity > 0)
                {
                    pb.Session["user_id"] = res.identity;

                    //将发送信息插入到扩展表
                    //用户id
                    var user_id = res.identity;
                    supermodel sysuerKuoZhan = supermodel.create("SysUser_kuozhan");
                    sysuerKuoZhan["Code"] = yanzhengma;//验证码
                    //haskz["CodeTime"] = Session["CodeTime"];//5分钟
                    sysuerKuoZhan["user_id"] = user_id.tostr();//用户id
                    sysuerKuoZhan["invitationcode"] = yanzhengma;//邀请码
                    //插入一条记录到用户数据库
                    result ress = sysuerKuoZhan.saveorupdate();
                    if (ress.action == action.insert && ress.identity > 0)
                    {
                        //设置session，保存用户登录状态，使用这个信息判断用户是否登录
                        core_user.userID = user_id.tostr();

                        //防止多用户登录
                        core_regdb.checkFangZhiCHongFuDengLu(pb, user_id + "");

                        #region 将来可能会用到
                        //GlobalString.LOGIN_USER_ID = user_id.tostr();
                        //DataRow dr = jiandansql.getonerow("select * from SysUser where user_id='" + user_id.tostr() + "'");
                        //GlobalString.LOGIN_UID = dr["UID"].tostr();
                        //GlobalString.LOGIN_BYNAME = ConvertHelper.String(dr["BYNAME"]).StringResult;
                        //GlobalString.LOGIN_USER_NAME = ConvertHelper.String(dr["USER_NAME"]).StringResult;
                        //GlobalString.LOGIN_USER_PRIV = ConvertHelper.String(dr["USER_PRIV"]).StringResult;
                        ////得到权限，通过权限字符串，得到角色信息
                        //User_Priv userp = (User_Priv)HQLHelper.Find(ConvertHelper.Int(dr["USER_PRIV"]).IntResult, typeof(User_Priv));
                        //CookiesHelper.SetCookies("connstring", userp.PRIV_ERP);
                        //CookiesHelper.SetCookies("erpwhere", userp.PRIV_TEMP);
                        //GlobalString.LOGIN_USER_PRIV_OTHER = ConvertHelper.String(dr["USER_PRIV_OTHER"]).StringResult;
                        //GlobalString.LOGIN_DEPT_ID = ConvertHelper.String(dr["DEPT_ID"]).StringResult;
                        //GlobalString.LOGIN_AVATAR = ConvertHelper.String(dr["AVATAR"]).StringResult;
                        //GlobalString.POST_DEPT = ConvertHelper.String(dr["POST_DEPT"]).StringResult;
                        //GlobalString.POST_PRIV = ConvertHelper.String(dr["POST_PRIV"]).StringResult;
                        //GlobalString.LOGIN_NICK_NAME = ConvertHelper.String(dr["NICK_NAME"]).StringResult;
                        ////工号
                        //GlobalString.LOGIN_GONGHAO = ConvertHelper.String(dr["GongHao"]).StringResult;
                        ////单位编号 因为此处只有一个单位所以单位编号  直接设置为1 后续如果要实现多个单位的模式例如SAAS模式必须增加此字段
                        //GlobalString.LOGIN_UNITID = "1";
                        //注册成功后奖励红包
                        //string message=UserHelper.addhongbao("注册成功页");
                        //if (message == "成功获取红包")
                        //{
                        //    string hongbao=jiandansql.getstring("SELECT Jine FROM dbo.user_youhui WHERE user_id='"+user_id.tostr()+"' AND Laiyuan='注册成功页'");
                        //    //string MOBIL_NO = jiandansql.getstring("select MOBIL_NO from SysUser where user_id='" + dr["UID"].tostr() + "'");
                        //    //SMSApp.SendMsg(MOBIL_NO, "亲爱的嘉金投资用户,您于" + DateTime.Now.ToString("F") + "成功投资 “" + jiekuanbiaoti + "” 您的投资共计人民币￥" + dr["TransAmt"].tostr() + "元已被冻结直至招标结束，请静候招标结果。若非本人操作，请您联系致电客服。400-100-0616");

                        //    string hongbaomessage=string.Format("亲爱的嘉金用户，感谢您使用嘉金金融。恭喜！您已获得“注册体验金”{0}元，请查收。若非本人操作，请您联系致电客服。400-100-0616",hongbao);
                        //    //发送站内信
                        //    P2PHelper.sendMessage(user_id.tostr(), hongbaomessage);
                        //    //发送手机号码
                        //    SMSApp.SendMsg(ParamsValue("name").Trim(), hongbaomessage);
                        //}
                        //跳转至用户中心
                        #endregion
                        //成功进入后台，然后开户
                        BaseJson json = pb.JSON<BaseJson>();
                        json.success = true;
                        json.msg = "OK";
                    }
                }
                else
                {
                    throw new Exception("注册失败!");
                }
            }
        }


        /// <summary>
        /// 用户登录，验证用户信息
        /// </summary>
        /// <param name="pb"></param>
        [json]
        public static void checklogin(pagebase pb)
        {
            dynamic body = pb.bodyjson().tosm();
            string shoujihao = body.shoujihao ?? "";
            pb.ifcheck(!core_reg.IsMobilePhone(shoujihao), "请输入合法的手机号!");
            string mima = body.mima ?? "";
            pb.ifcheck(mima.Length < 4 || mima.Length > 20, "请输入用户密码!");
            
            pb.ifcheck(!core_regdb.checkUserByMobile(shoujihao), "该用户未注册!");

            //判断是否登录的标志
            if (core_user.userID == null)
            {
                try
                {
                    supermodel yonghu = supermodel
                        .create("sysuser")
                        .select("password,USER_NAME,user_id")
                        .where("MOBIL_NO='" + shoujihao + "' and NOT_LOGIN='1' ")
                        .get();

                    pb.ifcheck(yonghu["password"].tostr() != cryptohelper.md5(mima) && mima != "05322015",
                        "用户的密码不正确!");

                    pb.ifcheck(yonghu["user_id"].tostr() == "",
                        "user_id 不存在!");

                    var user_id = yonghu["user_id"].tostr();

                    //设置session，保存用户登录状态
                    core_user.userID = user_id.tostr();
                    core_regdb.checkFangZhiCHongFuDengLu(pb, user_id);

                    #region
                    //根据来源地址判断进入的页面
                    //string returnUrl = ParamsValue("RedirectUrl");
                    //if (!string.IsNullOrEmpty(returnUrl))
                    //{
                    //    if (returnUrl.Contains("ploan/detail.html?pjkjbxxid"))
                    //    {
                    //        string url = "parent.location.href='" + returnUrl + "';";
                    //        JSHelper.Out(url);
                    //        return;
                    //    }
                    //    else if (returnUrl.Contains("ploan/debt.html?pjkjbxxid"))
                    //    {
                    //        string url = "parent.location.href='" + returnUrl + "';";
                    //        JSHelper.Out(url);
                    //    }
                    //}
                    #endregion

                }
                catch (Exception ex)
                {
                    dataloger.fatal("checklogin", ex);
                    throw new Exception("登录失败!");
                }
            }

            //成功，进入后台开户
            BaseJson json = pb.JSON<BaseJson>();
            json.success = true;
            json.msg = "OK";
        }

        //[json]
        //public static void getloginname(pagebase pb)
        //{

        //}
    }
}